/*
 * @Description:
 * @Author: Zzt
 * @Date: 2023-02-22 10:03:36
 * @LastEditTime: 2023-02-28 19:57:12
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import {
  CELECT_CHANNEL,
  GET_ANNOUNCE_LIST,
  SET_SELECT_KEY,
  SET_STATUS,
  GET_CHANNEL_LIST
} from '../constants';
import { AnnouncementReducer } from '../reducers/AnnouncementReducer';
import { fetchNoticeUserByPage } from '@/api/announcement/noticeUser';
import { fetchChannelList } from '@/api/announcement/channel';

const initialState = {
  selectItems: [],
  channelList: [],
  noticeTypeId: 0,
  announceList: [],
  status: 0
};
const AnnouncementContext = createContext();
const AnnouncementContextProvider = (props) => {
  const [state, dispatch] = useReducer(AnnouncementReducer, initialState);
  const actions = {
    /* 获取频道列表 */
    getChannelList() {
      fetchChannelList({}).then((res) => {
        const { data } = res;
        dispatch({ type: GET_CHANNEL_LIST, data });
      });
    },
    /* 列表选中的值 */
    setSelectChannelId(data) {
      dispatch({ type: CELECT_CHANNEL, data });
    },
    /* 设置选中列表 */
    setSelectKey(data) {
      dispatch({ type: SET_SELECT_KEY, data });
    },
    /* 获取通知列表 */
    getAnnounceList(params) {
      return new Promise((resolve, reject) => {
        fetchNoticeUserByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: GET_ANNOUNCE_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            dispatch({ type: GET_ANNOUNCE_LIST, data: [] });
            reject(err);
          });
      });
      // TODO 调取获取列表接口
    },
    setStatus(id) {
      dispatch({ type: SET_STATUS, data: id });
    }
  };
  useEffect(() => {}, []);
  return (
    <AnnouncementContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </AnnouncementContext.Provider>
  );
};
export const useAnnouncementContext = () => {
  return useContext(AnnouncementContext);
};
export { AnnouncementContext, AnnouncementContextProvider };
